package com.sita.cfmoto.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.sita.cfmoto.ErrorCode;
import com.sita.cfmoto.R;
import com.sita.cfmoto.persistence.User;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.Account;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.rest.model.request.UserRegisterRequest;
import com.sita.cfmoto.rest.model.response.Reply;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.Connectivity;
import com.sita.cfmoto.utils.JsonUtils;
import com.sita.cfmoto.utils.L;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.PersistUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Class RegisterActivity is for
 *
 * @author xiaodong on 15/3/2.
 */
public class RegisterActivity extends AppCompatActivity {

    @Bind(R.id.mobile)
    EditText mMobile;
    @Bind(R.id.password)
    EditText mPassword;
    @Bind(R.id.confirm_password)
    EditText mConfirmPassword;
    @Bind(R.id.agreement_link)
    TextView mLicense;
    //    @Bind(R.id.agreement_checkbox)
//    CheckBox mCheckbox;
    @Bind(R.id.checkcode)
    EditText mCheckCode;
    @Bind(R.id.button_resend_check_code)
    Button mBtnGetCheckCode;

    private boolean agreed = true;

    public static Intent newIntent() {
        return new Intent(GlobalContext.getGlobalContext(), RegisterActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);

//        ImageView imgBack = ((ImageView) findViewById(R.id.btn_back));
//        imgBack.setColorFilter(new LightingColorFilter(Color.WHITE, Color.WHITE));
//        imgBack.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                onBackPressed();
//            }
//        });

//        OverScrollDecoratorHelper.setUpOverScroll(mScrollView);
//
//        mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (isChecked) {
//                    agreed = true;
//                } else {
//                    agreed = false;
//                }
//            }
//        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        backToLogin();
    }

    @OnClick(R.id.btn_login)
    void onClickLogin() {
        backToLogin();
    }

    private void backToLogin() {
        startActivity(LoginActivity.newIntent());
        this.finish();
    }

    @OnClick(R.id.agreement_link)
    void clickAgreement() {
        // TODO: 2016/5/19 show license web page 
        AgreementDialog d = (AgreementDialog) getSupportFragmentManager()
                .findFragmentByTag("AgreementDialog");
        if (d == null) {
            d = new AgreementDialog();
        }
        d.show(getSupportFragmentManager(), "AgreementDialog");
//        try {
//            String url = "http://smartphone.yadea.com.cn:8080/yadea/app/agreement.html";
//            startActivity(WebActivity.newIntent(url, getString(R.string.user_agreement)));
//        } catch (ActivityNotFoundException e) {
//            LogUtils.d("register", "not found");
//        }
    }

    @OnClick(R.id.btn_register)
    void clickRegister() {
        String mobile = mMobile.getText().toString();
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11 || !mobile.startsWith("1")) {
            mMobile.setError(getText(R.string.error_invalid_mobile));
            mMobile.requestFocus();
            return;
        }
        if (mobile.length() > 11) {
            mobile = mobile.substring(0, 11);
            mMobile.setText(mobile);
            mMobile.requestFocus();
        }
        String checkcode = mCheckCode.getText().toString();
        if (TextUtils.isEmpty(checkcode)) {
            mCheckCode.setError(getText(R.string.error_check_code_empty));
            mCheckCode.requestFocus();
            return;
        }
        String password = mPassword.getText().toString();
        if (TextUtils.isEmpty(password)) {
            mPassword.setError(getText(R.string.error_invalid_password));
            mPassword.requestFocus();
            return;
        }
        String confirmPassword = mConfirmPassword.getText().toString();
        if (TextUtils.isEmpty(confirmPassword)) {
            mConfirmPassword.setError(getText(R.string.error_invalid_password));
            mConfirmPassword.requestFocus();
            return;
        }
        if (!confirmPassword.equals(password)) {
            mConfirmPassword.setError(getString(R.string.error_mismatch_password));
            mConfirmPassword.requestFocus();
            return;
        }

        if (!agreed) {
            ToastUtils.show(this, getText(R.string.error_must_accept_agreement));
            return;
        }

        if (!Connectivity.isConnected(this)) {
            ToastUtils.show(this, getText(R.string.must_enable_connectivity));
            return;
        }

        final MaterialDialog dialog = new MaterialDialog.Builder(this).title(R.string.user_register).content(R.string.registering)
                .progress(true, 15000)
                .build();
        dialog.show();

        UserRegisterRequest request = new UserRegisterRequest();
        request.mobile = mobile;
        request.password = password;
        request.smscode = checkcode;

        RestClient.getRestService().userRegister(request, new Callback<RestResponse>() {
                    @Override
                    public void success(RestResponse restResponse, Response response) {

                        if (response.getStatus() == 200) {
                            if (restResponse.mErrorCode.equals("0")) {
                                Gson gson = JsonUtils.getGson();
                                String s = gson.toJson(restResponse.mData);
                                Account account = gson.fromJson(s, Account.class);
                                User user = new User();
                                user.setAccountId(Long.valueOf(account.getAccountId()));
                                user.setEmail(account.getEmail());
                                user.setMobile(account.getMobile());
                                user.setAddress(account.getAddress());
                                user.setAvatar(account.getAvatar());
                                user.setBirthday(account.getBirthday());
                                user.setGender(account.getGender());
                                user.setNickName(account.getNickName());
                                user.setSignature(account.getSignature());
                                user.setUniqueId(account.getUniqueId());
                                user.setUserName(account.getUserName());
                                user.setXmppPass(account.getImPassword());
                                user.setXmppUser(account.getAccountId());

                                if (account != null) {
                                    PersistUtils.saveUser(user);
                                    registerSuccess(dialog);
                                } else {
                                    registerFailed(dialog);
                                }
                            } else {
                                registerFailed(dialog);
                            }
                        } else {
                            registerFailed(dialog);
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        L.e(error);
                        Reply reply = (Reply) error.getBodyAs(Reply.class);
                        if (dialog != null && !dialog.isCancelled()) {
                            dialog.dismiss();
                        }
                        if (reply != null) {
                            if (reply.errorCode.equals((ErrorCode.CAPTCHA_TIMEOUT_OR_ERROR))) {
                                Toast.makeText(RegisterActivity.this, getString(R.string.error_check_code_wrong), Toast.LENGTH_LONG).show();
                            } else if (reply.errorCode.equals(ErrorCode.MOBILE_EXIST)) {
                                Toast.makeText(RegisterActivity.this, getString(R.string.duplicated_mobile), Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(RegisterActivity.this, getString(R.string.register_failed), Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                }
        );
    }


    @OnClick(R.id.button_resend_check_code)
    void onClickResendCheckCode() {
        if (fakeCheckCode())
            return;

        String mobile = mMobile.getText().toString();
        if (TextUtils.isEmpty(mobile) || mobile.length() < 11 || !mobile.startsWith("1")) {
            mMobile.setError(getText(R.string.error_invalid_mobile));
            mMobile.requestFocus();
            return;
        }
        if (mobile.length() > 11) {
            mobile = mobile.substring(0, 11);
            mMobile.setText(mobile);
            mMobile.requestFocus();
        }

        RestClient.getRestService().getCheckCode(mobile, new Callback<RestResponse>() {
                    @Override
                    public void success(RestResponse restResponse, Response response) {
                        if (response.getStatus() == 200) {
                            if (restResponse.mErrorCode.equals("0")) {
                            }
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        L.e(error);
                        try {
                            Reply reply = (Reply) error.getBodyAs(Reply.class);
                            if (reply != null) {
                                if (reply.errorCode.equals((ErrorCode.SMS_CODE_IS_UNLAW))) {
                                    Toast.makeText(RegisterActivity.this, getString(R.string.error_check_code_wrong), Toast.LENGTH_LONG).show();
                                } else if (reply.errorCode.equals(ErrorCode.MOBILE_EXIST)) {
                                    Toast.makeText(RegisterActivity.this, getString(R.string.duplicated_mobile), Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(RegisterActivity.this, getString(R.string.error_check_code_get), Toast.LENGTH_LONG).show();
                                }
                            }
                        } catch (Exception e) {
                            Toast.makeText(RegisterActivity.this, getString(R.string.error_check_code_get), Toast.LENGTH_LONG).show();
                        }
                    }
                }
        );


        new CountDownTimer(120 * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mBtnGetCheckCode.setEnabled(false);
                String item = getString(R.string.check_code_resend, millisUntilFinished / 1000 - 1);
                mBtnGetCheckCode.setText(item);
            }

            @Override
            public void onFinish() {
                mBtnGetCheckCode.setEnabled(true);
                mBtnGetCheckCode.setText(getString(R.string.check_code_get));
            }
        }.start();
    }

    boolean fakeCheckCode() {
        mCheckCode.setText("1234");
        return true;
    }

    private void registerSuccess(MaterialDialog dialog) {
        if (dialog != null && !dialog.isCancelled()) {
            dialog.dismiss();
        }
        PersistUtils.saveUserStatus(LocalStorage.getAccountId(), Constants.USER_STATUS_REGISTERED);
//        startActivity(new Intent(RegisterActivity.this, BindingActivity.class));
        startActivity(LoginActivity.newIntent());
        this.finish();
    }

    private void registerFailed(MaterialDialog dialog) {
        if (dialog != null && !dialog.isCancelled()) {
            dialog.dismiss();
        }
    }
}
